package com.jt.aop;

import com.jt.pojo.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@Aspect
public class AOP {
    //设置静态map用以保存数据
    private static HashMap<Integer, Object> hashMap = new HashMap<>();

    @Pointcut("@annotation(com.jt.anno.Cache)")
    public void poincut(){

    }

    @Pointcut("execution(* com.jt.service..*(..))")
    public void execution_point(){

    }

//    @Around("execution_point()")
    @Around("poincut()")
    public Object Around(ProceedingJoinPoint joinPoint){
        Object result = null;
        //获取参数
        Object[] args = joinPoint.getArgs();
        //将参数转为user类
        User arg = (User) args[0];
        //标记缓存是否命中
//        Boolean flag = false;

        //尝试从缓存中取，若有则flag设为true，若无则flag不变

//        for (Map.Entry<Integer, Object> entry : hashMap.entrySet()) {
//            if (entry.getKey()==arg.getId()){
//                flag = true;
//            }
//        }

        try {
            if (hashMap.containsKey(arg.getId())){
                System.out.println("执行缓存");
                System.out.println(hashMap.get(arg.getId()));
                return hashMap.get(arg.getId());
            }else {
                result = joinPoint.proceed();
                hashMap.put(arg.getId(), arg);
            }
//            //检测flag
//            if (flag==true){    //为true，直接取
//                Object value = hashMap.get(arg.getId());
//                System.out.println("执行缓存"+value);
////                for (Map.Entry<Integer, Object> entry : hashMap.entrySet()) {
////                    if (entry.getKey()==arg.getId()){
////                        System.out.println("执行缓存"+entry.getValue());
////                    }
////                }
//            }else {     //为false，执行目标方法并存入缓存
//                //则保存到缓存
//                joinPoint.proceed();
//                hashMap.put(arg.getId(), arg);
//            }
        }catch (Throwable throwable){
            throwable.printStackTrace();
        }
        return result;
    }
}
